/*
 *所有关于Quality_TestMaterial类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*Quality_TestMaterialService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using iMES.Core.BaseProvider;
using iMES.Core.Extensions.AutofacManager;
using iMES.Entity.DomainModels;
using System.Linq;
using iMES.Core.Utilities;
using System.Linq.Expressions;
using iMES.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Yun.Quality.IRepositories;
using iMES.Core.Enums;
using System.Collections.Generic;
using System.Threading.Tasks;
using Yun.Quality.Repositories;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using iMES.Custom.IRepositories;

namespace Yun.Quality.Services
{
    public partial class Quality_TestMaterialService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IQuality_TestMaterialRepository _repository;//访问数据库
        private readonly IQuality_TestPlanRepository _planRepository;//访问数据库
        private readonly IBase_NumberRuleRepository _numberRuleRepository;//自定义编码规则访问数据库
        [ActivatorUtilitiesConstructor]
        public Quality_TestMaterialService(
            IQuality_TestMaterialRepository dbRepository,
              IQuality_TestPlanRepository planRepository,
            IHttpContextAccessor httpContextAccessor,
                       IBase_NumberRuleRepository numberRuleRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _planRepository = planRepository;
            _repository = dbRepository;
            _numberRuleRepository = numberRuleRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }


        /// <summary>
        /// 获取table1的数据
        /// </summary>
        /// <param name="loadData"></param>
        /// <returns></returns>
        public async Task<object> GetTable1Data(PageDataOptions loadData)
        {
            //Equip_SpotMaintPlanModelBody.vue中loadTableBefore方法查询前给loadData.Value写入的值
            List<where> list = loadData.Wheres.DeserializeObject<List<where>>();
            //获取查询到的总和数
            int total = await Quality_TestPlanRepository.Instance.FindAsIQueryable(x => x.QualityTestPlanId == new Guid(list[0].value)).CountAsync();

            var data = await Quality_TestPlanRepository.Instance
                //这里可以自己查询条件，从 loadData.Value找前台自定义传的查询条件
                .FindAsIQueryable(x => x.QualityTestPlanId == new Guid(list[0].value))
                //分页
                .TakeOrderByPage(1, 10, x => new Dictionary<object, QueryOrderBy>() { { x.CreateDate, QueryOrderBy.Desc } })
                .Select(s => new { s.QualityTestPlanId, s.QualityTestPlanName, s.QualityTestPlanCode, s.QualityTestPlanEnable, s.QualityTestGroup, s.CreateID, s.Creator, s.CreateDate, s.ModifyID, s.Modifier, s.ModifyDate })
                .ToListAsync();
            object gridData = new { rows = data, total };
            return gridData;
        }



        /// <summary>
        /// 获取table2的数据
        /// </summary>
        /// <param name="loadData"></param>
        /// <returns></returns>
        public async Task<object> GetTable2Data(PageDataOptions loadData)
        {
            //Equip_SpotMaintPlanModelBody.vue中loadTableBefore方法查询前给loadData.Value写入的值
            //获取查询到的总和数
            List<where> list = loadData.Wheres.DeserializeObject<List<where>>();
            //获取查询到的总和数
            int total = await repository.DbContext.Set<Quality_TestDetail>().Where(x => x.QualityTestDetailId == new Guid(list[0].value)).CountAsync();
            //从 loadData.Value取查询条件，分页等信息
            //这里可以自己查询条件，从 loadData.Value找前台自定义传的查询条件
            var data = await repository.DbContext.Set<Quality_TestDetail>().Where(x => x.QualityTestDetailId == new Guid(list[0].value))
                //分页
                .TakeOrderByPage(1, 10, x => new Dictionary<object, QueryOrderBy>() { { x.TestDetailNum, QueryOrderBy.Desc } })
                .Select(s => new { s.QualityTestDetailId, s.QualityTestMaterialId, s.TestDetailNum, s.TestDetailNumOK, s.TestDetailNumNo, s.Qualityinspector, s.Detailedremarks, s.TestDetailResult })
                .ToListAsync();
            object gridData = new { rows = data, total };
            return gridData;
        }
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            // 取出校验完成后的从表数据
            TableExtra tableExtra = saveDataModel.Extra.ToString().DeserializeObject<TableExtra>();

            // 保存到数据库前的逻辑
            AddOnExecuting = (Quality_TestMaterial mainEntity, object obj) =>
            {
                if (string.IsNullOrWhiteSpace(mainEntity.QualityTestMaterialCode))
                    mainEntity.QualityTestMaterialCode = GetSpotMaintPlanCode();

                // 检查主表中是否存在重复的编码
       
                return WebResponseContent.Instance.OK();
            };

            // 保存到数据库后的逻辑
            AddOnExecuted = (Quality_TestMaterial mainEntity, object obj) =>
            {
                // 保存从表1数据
                List<Quality_TestDetail> detail1List = tableExtra.Table1List.Select(s => new Quality_TestDetail
                {
                    QualityTestDetailId = s.QualityTestDetailId,
                    QualityTestMaterialId = mainEntity.QualityTestMaterialId,
                    TestDetailNum = s.TestDetailNum,
                    TestDetailNumOK = s.TestDetailNumOK,
                    TestDetailNumNo = s.TestDetailNumNo,
                    Qualityinspector = s.Qualityinspector,
                    Detailedremarks = s.Detailedremarks,
                    TestDetailResult = s.TestDetailResult
                }).ToList();

                // 筛选新增数据
                List<Quality_TestDetail> addDetail1List = detail1List.Where(x => x.QualityTestDetailId == new Guid("00000000-0000-0000-0000-000000000000")).ToList();
                addDetail1List.ForEach(x => { x.SetCreateDefaultVal(); });
                _repository.AddRange(addDetail1List);

                //// 保存从表2数据
                //List<Quality_TestPlan> detail2List = tableExtra.Table2List.Select(s => new Quality_TestPlan
                //{
                //    QualityTestPlanId = s.QualityTestPlanId,
                //    QualityTestMaterialId = mainEntity.QualityTestMaterialId,
                //    QualityTestPlanName = s.QualityTestPlanName,
                //    QualityTestPlanCode = s.QualityTestPlanCode,
                //    QualityTestPlanEnable = (int)s.QualityTestPlanEnable,
                //    QualityTestGroup = s.QualityTestGroup,
                //}).ToList();

                //// 筛选新增数据
                //List<Quality_TestPlan> addDetail2List = detail2List.Where(x => x.QualityTestPlanId == new Guid("00000000-0000-0000-0000-000000000000")).ToList();
                //addDetail2List.ForEach(x => { x.SetCreateDefaultVal(); });
                //_repository.AddRange(addDetail2List);

                //// 最终保存
                _repository.SaveChanges();
                return WebResponseContent.Instance.OK();
            };

            return base.Add(saveDataModel);
        }

        /// <summary>
        /// 自动生成设备编号
        /// </summary>
        /// <returns></returns>
        public string GetSpotMaintPlanCode()
        {
            DateTime dateNow = (DateTime)DateTime.Now.ToString("yyyy-MM-dd").GetDateTime();
            //查询当天最新的订单号
            string defectItemCode = repository.FindAsIQueryable(x => x.CreateDate > dateNow && x.QualityTestMaterialCode.Length > 8)
                .OrderByDescending(x => x.QualityTestMaterialCode)
                .Select(s => s.QualityTestMaterialCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "Device")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    rule += (defectItemCode.Substring(defectItemCode.Length - numberRule.SerialNumber).GetInt() + 1).ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }
                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }

        public class Table1
        {


            /// <summary>
            ///质检明细主键Id
            /// </summary>
            [Key]
            [Display(Name = "质检明细主键Id")]
            [Column(TypeName = "uniqueidentifier")]
            [Required(AllowEmptyStrings = false)]
            public Guid QualityTestDetailId { get; set; }

            /// <summary>
            ///原料质检Id
            /// </summary>
            [Display(Name = "原料质检Id")]
            [Column(TypeName = "uniqueidentifier")]
            public Guid? QualityTestMaterialId { get; set; }
            /// <summary>
            ///质检数量
            /// </summary>
            [Display(Name = "质检数量")]
            [Column(TypeName = "int")]
            [Editable(true)]
            public int? TestDetailNum { get; set; }

            /// <summary>
            ///合格数量
            /// </summary>
            [Display(Name = "合格数量")]
            [Column(TypeName = "int")]
            [Editable(true)]
            public int? TestDetailNumOK { get; set; }

            /// <summary>
            ///不合格数量
            /// </summary>
            [Display(Name = "不合格数量")]
            [Column(TypeName = "int")]
            [Editable(true)]
            public int? TestDetailNumNo { get; set; }

            /// <summary>
            ///质检人
            /// </summary>
            [Display(Name = "质检人")]
            [MaxLength(200)]
            [Column(TypeName = "nvarchar(200)")]
            [Editable(true)]
            [Required(AllowEmptyStrings = false)]
            public string Qualityinspector { get; set; }

            /// <summary>
            ///备注
            /// </summary>
            [Display(Name = "备注")]
            [MaxLength(200)]
            [Column(TypeName = "nvarchar(200)")]
            [Editable(true)]
            [Required(AllowEmptyStrings = false)]
            public string Detailedremarks { get; set; }

            /// <summary>
            ///质检结果
            /// </summary>
            [Display(Name = "质检结果")]
            [MaxLength(200)]
            [Column(TypeName = "nvarchar(200)")]
            [Editable(true)]
            [Required(AllowEmptyStrings = false)]
            public string TestDetailResult { get; set; }


        }
        //public class Table2
        //{
        //    /// <summary>
        //    ///质检方案主键
        //    /// </summary>
        //    [Key]
        //    [Display(Name = "质检方案主键")]
        //    [Column(TypeName = "uniqueidentifier")]
        //    [Editable(true)]
        //    [Required(AllowEmptyStrings = false)]
        //    public Guid QualityTestPlanId { get; set; }

        //    /// <summary>
        //    ///原料质检Id
        //    /// </summary>
        //    [Display(Name = "原料质检Id")]
        //    [Column(TypeName = "uniqueidentifier")]
        //    public Guid? QualityTestMaterialId { get; set; }
        //    /// <summary>
        //    ///质检方案名称
        //    /// </summary>
        //    [Display(Name = "质检方案名称")]
        //    [MaxLength(100)]
        //    [Column(TypeName = "nvarchar(100)")]
        //    [Editable(true)]
        //    public string QualityTestPlanName { get; set; }

        //    /// <summary>
        //    ///质检方案编码
        //    /// </summary>
        //    [Display(Name = "质检方案编码")]
        //    [MaxLength(100)]
        //    [Column(TypeName = "nvarchar(100)")]
        //    [Editable(true)]
        //    public string QualityTestPlanCode { get; set; }

        //    /// <summary>
        //    ///质检状态
        //    /// </summary>
        //    [Display(Name = "质检状态")]
        //    [Column(TypeName = "int")]
        //    [Editable(true)]
        //    public int? QualityTestPlanEnable { get; set; }

        //    /// <summary>
        //    ///质检组
        //    /// </summary>
        //    [Display(Name = "质检组")]
        //    [MaxLength(200)]
        //    [Column(TypeName = "nvarchar(200)")]
        //    [Editable(true)]
        //    public string QualityTestGroup { get; set; }

           

         
        //}

        public class TableExtra
        {
            /// <summary>
            /// 从表1
            /// </summary>
            public List<Table1> Table1List { get; set; }

            /// <summary>
            /// 从表2
            /// </summary>
            //public List<Table2> Table2List { get; set; }
        }
        public class where
        {
            public string name { get; set; }
            public string value { get; set; }
        }
    }
}
